package com.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

/**
 * 全局session校验
 */
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		Object object = request.getSession().getAttribute("session_user");
		//不存在的话，跳转到登录界面
		if (object == null) {
			String defaultFailureUrl = "/user/login";
			log.info("被拦截地址-->" + request.getRequestURI());
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
			log.info("base Path:[{}]",basePath);
			PrintWriter out = response.getWriter();
			StringBuilder builder = new StringBuilder();
			builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
			builder.append("alert(\"页面过期，请重新登录\");");
			builder.append("window.top.location.href=\"");
			builder.append(defaultFailureUrl);
			builder.append("\";</script>");
			out.print(builder.toString());
			out.close();
			return false;
		} else {
			//存在session，放行通过
			return true;
		}


//		Object user = request.getSession().getAttribute("session_user");
//		if (user == null) {
//			request.setAttribute("msg", "没有权限请先登陆");
//			request.getRequestDispatcher("/login.html").forward(request, response);
//			return false;
//		} else {
//			return true;
//		}
	}



}
